from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

from passlib.context import CryptContext
from typing import Union, Annotated
from datetime import timedelta, datetime
from jose import JWTError, jwt

from src.config import SECRET_KEY, ALGORITHM
from src.database.repositories import UserRepository
from src.schemas import User


CURRENT_PREFIX = "auth"

oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{CURRENT_PREFIX}/token")

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def verify_password(plain_password: Union[str, bytes], hashed_password: Union[str, bytes]):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password: Union[str, bytes]):
    return pwd_context.hash(password)


def create_access_token(data: dict, expires_delta: timedelta):
    to_encode = data.copy()
    expire = datetime.utcnow() + expires_delta

    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

    return encoded_jwt


async def authenticate_user(username: str, password: str):
    user = await UserRepository(username).get()

    if not user:
        return False
    if not verify_password(password, user.password_hash):
        return False
    
    return user


async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )

    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception
    
    user = await UserRepository(username).get()

    if user is None:
        raise credentials_exception
    
    user_schema = User(id=user.id, username=user.username)
    
    return user_schema
